# Django
from django import forms
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib import auth
from scopo.models import Result
from django.core import serializers
# PuppyIR Service
from scopo.service import service
# Python import
import base64

def index(request):
    """show base index view"""
    context = RequestContext(request)
    return render_to_response('scopo/index.html', context)

def query(request):
    """show results for query"""
    aquery = request.POST['query']
    results = service.search(aquery)
    context = RequestContext(request)
    return render_to_response('scopo/results.html', 
        {'query': aquery, 'results': results.items}, context)
		
@login_required
def view_saved(request):
	context = RequestContext(request)
	username = request.user.username
	results = Result.objects.filter(result_id__username = username)
	return render_to_response('scopo/saved.html', {'username': username, 'results':results},
			context) 
def login(request):
	context = RequestContext(request)
	return render_to_response('scopo/login.html', context)
def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/scopo/")
    else:
        form = UserCreationForm()
    return render_to_response("scopo/register.html", {
        'form': form,
    }, RequestContext(request))

def logout_view(request):
	auth.logout(request)
	return HttpResponseRedirect("/scopo/loggedout/")
	
@login_required
def ajaxsave(request):
    mytitle = request.POST['title']
    mydesc = request.POST['description']
    myuser = request.user
    encoded =  base64.b64encode(mytitle)
    if len(Result.objects.filter(result_encoded = encoded)) == 0:
       r = Result(result_id = myuser, result_title = mytitle, result_description = mydesc, result_encoded = encoded)
       r.save()
    results = Result.objects.filter(result_id__username = myuser.username)
    resultvalues = serializers.serialize('json', results, fields= ('result_title'))
    return HttpResponse(resultvalues, mimetype='application/json')
	
@login_required
def ajaxget(request):
    username = request.user.username
    results = Result.objects.filter(result_id__username = username)
    resultvalues = serializers.serialize('json', results, fields= ('result_title'))
    return HttpResponse(resultvalues, mimetype='application/json')

	
    
    
    
